package java7;

/**
 * @author lwx
 * @create 2018-06-22 15:11
 */
public class AddSuppressedTest {

    public void show() throws BaseException {
        try {
            Integer.parseInt("Hello");
        } catch (NumberFormatException e1) {
            throw new BaseException(e1);
        } finally {
            try {
                int result = 2 / 0;
            } catch (ArithmeticException e2) {
                throw new BaseException(e2);
            }
        }
    }

    public void show2() throws Exception {
        Exception ex = null;
        try {
            Integer.parseInt("Hello");
        } catch (NumberFormatException e1) {
            // throw new BaseException(e1);
            ex = e1;
        } finally {
            try {
                int result = 2 / 0;
            } catch (ArithmeticException e2) {
                // throw new BaseException(e2);
                if (ex != null) {
                    ex.addSuppressed(e2);

                } else {

                    ex = e2;
                }
            }
        }
        if (ex != null) {

            throw ex;
        }

    }

    public static void main(String[] args) throws Exception {
        AddSuppressedTest d = new AddSuppressedTest();
       // d.show();//抛出ArithmeticException  ，try里头的异常被顶掉了
        //JD7之前的做法
        /**
         * 伪代码实现
         * Exception ex=null;
         *
         * try{
         *
         *     ex=异常1
         *
         * }catch(Exception e){
         *
         *     ex =异常2
         * }finally{
         *      if(ex==null){//开关，如果try有异常，用于忽略finally中的异常
         *     ex=异常3
         *     }
         *
         * }
         * if(ex != null){
         throw new BaseException(ex);
         }
         class  BaseException extends Exception{
         }
         *
         * */



        d.show2();

        //NumberFormatException  ArithmeticException
    }


}

class BaseException extends Exception {
    public BaseException(Exception ex) {
        super(ex);
    }

}
